#include<stdio.h>
#include "../include/vfs.h"
#include<stdlib.h>
#include<string.h>



int addfiles(char path[], char filename[], char file_path[])

{


	FILE *fp,*add;
	int i,j,k=0,index=0,del_len,len;
	long recsize,pos;
	FD *fd,*exist,*exist1=NULL;
	char *data,ch,*make,new_path[100],send[20],*check;
	Block *b;

	if(!valid_name(filename))
		return 2;

	fp = fopen(filesystem_name,"r+b");

	header=malloc(sizeof(Header));

	fread(header,sizeof(Header),1,fp);

	exist =(FD*)malloc(sizeof(FD));

	add = fopen(file_path,"rb");

	if(add==NULL)
	{
		//printf("\n BYE");
		return 5;
	}

	recsize=sizeof(Block);

	if(path[strlen(path)-1]=='/' && strlen(path)>2)
	{
		path[strlen(path)-1]='\0';

	}
	
	/*if(path[strlen(path)-1]=='/' && strlen(path)>2)
	{
		strcpy(new_path,path);
		new_path[strlen(new_path)-1]='\0';
		path[strlen(path)-1]='\0';

		//printf("\n PATH:%s",path);
		strcpy(exist->path,path);
		strcat(path,"/");
		strcat(path,filename);
		

	}
	*/
		
		strcpy(exist->path,path);
		strcpy(new_path,path);
	
		if(strcmp(path,"/")!=0)
			strcat(path,"/");
	
		strcat(path,filename);

	//printf("\nFULL PATH:%s",path);
		
		exist1 = search(roots.naryroot,exist);

		if(exist1==NULL)
		{
			//printf("\n EXIST NULL");
			makedir(new_path,"");
			
		}
		strcpy(exist->path,path);

		exist1 = search(roots.naryroot,exist);

		if(exist1!=NULL)
			return 3;
	
	fseek(add,0,SEEK_END);
	pos = ftell(add);

	if(pos>1024)
		return 6;

	data = malloc(pos*sizeof(char));

	//printf("\n POS:%ld",pos);
	rewind(add);


    	//while (1)
    	{	
		//if(k>1000)
		//	return 6;

		fread(data,sizeof(char),pos,add);
		//ch = fgetc(add);

		//if(ch==EOF)
		//break;

		
		//printf("\n CHAR:%c",ch);

		//data[k]=ch;
		//strcat(data,ch);

		//printf("\n ADDING %c",data[k]);
		//k++;
		
		
	}

	//printf("\n DATA:%s",data);
		

				for(i=0;i<header->max_FD;i++)
				{
					if(header->fd_list[i].block_no==0)
					{
						fd=(FD*)malloc(sizeof(FD));
						strcpy(fd->filename,filename);
						strcpy(fd->path,path);
						fd->file_type =2;
						fd->file_size=strlen(data);
						break;
					}

				}

	
					for(j=0;j<header->num_blocks;j++)
					{
						if(header->freelist[j].isfree==1)
						{

							fd->block_no=header->freelist[j].block;
							header->freelist[j].isfree=0;
							
							break;
						}
					}

					if(j==header->num_blocks)
						return 4;
					
					roots.naryroot=add_node(roots.naryroot,fd,0);
					roots.bstRoot=insert(roots.bstRoot,fd);
					hashtable_insert(fd);

					
			b=(Block*)malloc(sizeof(Block));
			strcpy(b->buffer,data);
		//	printf("\n BUFFER:%s",b->buffer);
			b->num = j+1;
		
			fseek(fp,j*recsize,SEEK_CUR); 
			fwrite(b,sizeof(Block),1,fp);
		

	rewind(fp);
	fwrite(header,sizeof(Header),1,fp);

	fclose(fp);


	return 0;

}
